package network;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Logger;

/**
 * 扫描localhost上1~1024的端口，查看哪些端口被绑定
 */
public class PortScanner {

    //默认是ConsoleHandler，Level是info
    private static Logger logger = Logger.getLogger(PortScanner.class.getPackage().getName());

    //扫描本地主机上的1~1024的端口
	public void scan() {
		Socket socket = null;
		for (int i = 1; i < 1024; i++) {
			try {
				socket = new Socket("127.0.0.1", i);
				System.out.println("There is a server on port:" + i);
			} catch (IOException ioe) {
				System.out.println("Can not connect to the port:" + i);
			}finally{
				if(socket != null)
					try {
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
			}
		}
	}


	public static void main(String[] args) throws IOException {
        logger.info("扫描端口");
		new PortScanner().scan();

        logger.info("InetAddress使用");
		InetAddress inet = InetAddress.getLocalHost();
		System.out.println(inet);
        logger.info("baidu.com的InetAddress");
		inet = InetAddress.getByName("www.baidu.com");
		System.out.println(inet);
        System.out.println(inet.getHostAddress());
        System.out.println(inet.getHostName());
        System.out.println(inet.getCanonicalHostName());
	}
	
}
